//package com.ophiux.utils.aspect;
//
//import javax.servlet.ServletRequest;
//import javax.servlet.ServletResponse;
//import javax.servlet.http.HttpServletRequest;
//
//import org.apache.shiro.SecurityUtils;
//import org.aspectj.lang.ProceedingJoinPoint;
//import org.aspectj.lang.annotation.Around;
//import org.aspectj.lang.annotation.Aspect;
//import org.aspectj.lang.annotation.Pointcut;
//import org.springframework.stereotype.Component;
//import org.springframework.web.context.request.RequestContextHolder;
//import org.springframework.web.context.request.ServletRequestAttributes;
//import org.springframework.web.multipart.MultipartFile;
//
//import com.alibaba.fastjson.JSON;
//import com.esiran.common.entity.APIException;
//import com.esiran.system.entity.User;
//
//import lombok.extern.slf4j.Slf4j;
//
//@Aspect
//@Component
//@Slf4j
//public class RequestMappingAspect {
//	
//	@Pointcut("@annotation(org.springframework.web.bind.annotation.GetMapping)")
//    public void getMapping() {
//	}
//	
//	@Pointcut("@annotation(org.springframework.web.bind.annotation.PostMapping)")
//    public void postMapping() {
//	}
//	
//	@Pointcut("@annotation(org.springframework.web.bind.annotation.PutMapping)")
//    public void putMapping() {
//	}
//	
//	@Pointcut("@annotation(org.springframework.web.bind.annotation.DeleteMapping)")
//    public void deleteMapping() {
//	}
//	
////	@Pointcut("execution(* com.esiran.greenadmin.admin.controller..*.*(..))")
////    public void restController() {
////	}
//
//	
//	@Around("deleteMapping() || postMapping() || putMapping()")
//	public Object doBefore(ProceedingJoinPoint joinPoint) throws APIException, Exception {
//		Object result = "";
//		try {
//			ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//	        HttpServletRequest request = attributes.getRequest();
//	        
//			String className = joinPoint.getSignature().getDeclaringTypeName();
//			String methodName = joinPoint.getSignature().getName();
//			Object[] methodArgs = joinPoint.getArgs();
//	        Object[] arguments  = new Object[methodArgs.length];
//	        
//	        User user = null;
//	        try {
//	        	user = (User) SecurityUtils.getSubject().getPrincipal();
//				if(user != null) {
//					log.info("该用户:{},正在进行{}请求，接口方法:{}",user.getUsername(),request.getMethod(),request.getRequestURL().toString());
//				}
//			} catch (Exception e) {
//			}
//	        /**
//        	 * 获取方法的参数值数组
//        	 */
//            log.info("请求连接 {}",request.getRequestURL().toString());
//            log.info("请求ip={}",getIpAddress(request));
//            log.info("请求类型 {}",request.getMethod());
//            log.info("请求方法 {}.{}",className,methodName);
//            log.info("请求token={}",request.getHeader("Authorization"));
//            
//			for (int i = 0; i < methodArgs.length; i++) {
//				if (methodArgs[i] instanceof ServletRequest || methodArgs[i] instanceof ServletResponse || methodArgs[i] instanceof MultipartFile) {
//					//ServletRequest不能序列化，从入参里排除，否则报异常：java.lang.IllegalStateException: It is illegal to call this method if the current request is not in asynchronous mode (i.e. isAsyncStarted() returns false)
//	                //ServletResponse不能序列化 从入参里排除，否则报异常：java.lang.IllegalStateException: getOutputStream() has already been called for this response
//					continue;
//				}
//				arguments[i] = methodArgs[i];
//			}
//			String paramter = "";
//	        if (arguments != null) {
//	            try {
//	                paramter = JSON.toJSONString(arguments);
//	            } catch (Exception e) {
//	                paramter = arguments.toString();
//	            }
//	        }
//            log.info("请求入参 {}", paramter);
//        	
//        	//可以添加日志表
//            //记录用户 轨迹
//            // 先进 filter 在进 interceptor 最后进 aop
//            // 可以通过 token 拦截，然后 通过token 获取用户数据 在aop 中 获取 user 数据
//        	
//        	//执行业务方法
//           	result = joinPoint.proceed();
//        	
//        	log.info("方法\n"+className+"."+methodName+"()--->\n响应参数："+ JSON.toJSONString(result));
//		} catch (APIException e) {
//			log.info("接收程序抛出的异常，msg={},code={}",e.getMessage(),e.getCode());
//			throw new APIException(e.getMessage(), e.getCode());
//		} catch (Throwable e) {
//			log.info("执行joinPoint.proceed()异常",e);
//			throw new APIException("操作失败", "ERROR");
//		}
//		return result;
//	}
//	
//	@Around("getMapping()")
//	public Object doBeforeGet(ProceedingJoinPoint joinPoint) throws APIException, Exception {
//		Object result = "";
//		try {
//			ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//	        HttpServletRequest request = attributes.getRequest();
//	        
//			String className = joinPoint.getSignature().getDeclaringTypeName();
//			String methodName = joinPoint.getSignature().getName();
//			Object[] methodArgs = joinPoint.getArgs();
//	        Object[] arguments  = new Object[methodArgs.length];
//	
//	        /**
//	    	 * 获取方法的参数值数组
//	    	 */
//	        log.info("请求连接 {}",request.getRequestURL().toString());
//	        log.info("请求ip={}",getIpAddress(request));
//	        log.info("请求类型 {}",request.getMethod());
//	        log.info("请求方法 {}.{}",className,methodName);
//	        log.info("请求token={}",request.getHeader("Authorization"));
//			for (int i = 0; i < methodArgs.length; i++) {
//				if (methodArgs[i] instanceof ServletRequest || methodArgs[i] instanceof ServletResponse || methodArgs[i] instanceof MultipartFile) {
//					//ServletRequest不能序列化，从入参里排除，否则报异常：java.lang.IllegalStateException: It is illegal to call this method if the current request is not in asynchronous mode (i.e. isAsyncStarted() returns false)
//	                //ServletResponse不能序列化 从入参里排除，否则报异常：java.lang.IllegalStateException: getOutputStream() has already been called for this response
//					continue;
//				}
//				arguments[i] = methodArgs[i];
//			}
//			String paramter = "";
//	        if (arguments != null) {
//	            try {
//	                paramter = JSON.toJSONString(arguments);
//	            } catch (Exception e) {
//	                paramter = arguments.toString();
//	            }
//	        }
//	        log.info("请求入参 {}", paramter);
//	    	//执行业务方法
//			result = joinPoint.proceed();
////			log.info("方法\n"+className+"."+methodName+"()--->\n响应参数："+ JSON.toJSONString(result));
//		} catch (Throwable e) {
//			log.info("执行joinPoint.proceed()异常",e);
//			throw new APIException("操作失败", "ERROR");
//		}
//		return result;
//	}
//	
//	
//	/**
//     * 获取请求实际ip
//     *
//     * @param request
//     * @return
//     */
//    public static String getIpAddress(HttpServletRequest request) {
//        String ip = request.getHeader("x-forwarded-for");
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getHeader("Proxy-Client-IP");
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getHeader("WL-Proxy-Client-IP");
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getHeader("HTTP_CLIENT_IP");
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getRemoteAddr();
//        }
//        return ip;
//    }
//}
